//
//  IOAResponse.m
//  IOAMall
//
//  Created by Mac on 2018/3/5.
//  Copyright © 2018年 Mac. All rights reserved.
//

#import "IOAResponse.h"

@implementation IOAResponse

+ (IOAResponse *)responseWithRequest:(IOARequest *)request {
    if (!request) return nil;
    IOAResponse *response = [IOAResponse new];
    [response updateStatusCodesWithRequest:request];
    
    return response;
}

- (void)updateStatusCodesWithRequest:(IOARequest *)request {
    NSInteger statusCode = [request responseStatusCode];
    self.serverResponseStatusCode = statusCode;
    self.responseMessage = @"网络异常";
    
    if (statusCode == 0) { // 网络异常
        self.responseMessage = @"网络异常";
        self.responseStatusType = ResponseStatusTypeNoNetwork;
        return;
    }

    if (statusCode == 200) {
        self.requestResponseStatusCode = request.serverRequestStatusCode;
        if (request.serverRequestStatusCode == 1002) { // 登录过期
            self.responseMessage = request.serverResponseMessage;
            self.responseStatusType = ResponseStatusTypeExpiryToken;
            return;
        }
        
        if (request.serverRequestStatusCode == 1003) { // 用户不存在
            self.responseMessage = request.serverResponseMessage;
            self.responseStatusType = ResponseStatusTypeNonExistent;
            return;
        }
        
        if (request.serverRequestStatusCode == 1004) { // 用户不存在
            self.responseMessage = request.serverResponseMessage;
            self.responseStatusType = ResponseStatusTypeRequestError;
            return;
        }
        
        if (request.serverRequestStatusCode == 1007) { // 未实名认证
            if (request.serverResponseMessage.length) {
                self.responseMessage = request.serverResponseMessage;
            }
            self.responseStatusType = ResponseStatusTypeUnauthorized;
            return;
        }
        
    }
}

// 是否需要提示
- (BOOL)alertOrNot {
    if (!(self.responseStatusType == ResponseStatusTypeNoNetwork ||
          self.responseStatusType == ResponseStatusTypeExpiryToken ||
          self.responseStatusType == ResponseStatusTypeUnauthorized)) {
        return YES;
    }
    
    return NO;
}

// 判断网络状态
- (BOOL)isNoNetwork {
    if (self.responseStatusType == ResponseStatusTypeNoNetwork) {
        return YES;
    }
    
    return NO;
}

// 是否token失效
- (BOOL)isExpiryToken {
    if (self.responseStatusType == ResponseStatusTypeExpiryToken) {
        return YES;
    }
    
    return NO;
}

// 后台服务错误
- (BOOL)isRequestServerError {
    if (self.responseStatusType == ResponseStatusTypeRequestError) {
        return YES;
    }
    
    return NO;
}

// 服务器错误
- (BOOL)isServerServiceError {
    if (self.responseStatusType == 500) {
        return YES;
    }
    
    return NO;
}

// 该目标已存在
- (BOOL)isTargetExist {
    return NO;
}

@end
